require('../fonts/iconfont.css')
require('../less/personalInfo.less')

// 引入weui
require('weui')
// 引入weui.js
import weui from 'weui.js';



// 入口函数
document.ready(function () {
    //加载导航守卫
    utils.navGuard()

    // 获取用户id
    const userId = localStorage.getItem('userId')
    // 获取点击返回我的页面
    const returnmine = document.querySelector('.returnmine')
    // 用户名
    const nickname = document.querySelector('#nickname')
    // 头像
    const userimg = document.querySelector('.userimg')
    //获取隐藏的input 文件上传
    const file = document.querySelector('#file')
    // 性别
    const gender = document.querySelector('#gender')
    // 生日
    const birthday = document.querySelector('#birthday')
    //城市
    const address = document.querySelector('#address')
    //获取个性签名
    const signature = document.querySelector('#signature')
    //获取文本域
    const textarea = document.querySelector('.weui-textarea')
    //获取文字
    const text = document.querySelector('#text')
    //保存信息
    const save = document.querySelector('.save')

    // 渲染个人信息
    function getuserdata() {
        // 数据回填
        const userdata = JSON.parse(localStorage.getItem('userInfo'))
        if (userdata.imgurl) {
            userimg.src = 'http://139.9.177.51:8099/' + userdata.imgurl
            nickname.value = userdata.nickname
            gender.textContent = userdata.gender
            signature.value = userdata.sign
            birthday.textContent = userdata.birthday.substr(0, 10)
            address.textContent = userdata.address.replace(',', '-')
        }
    }
    getuserdata();

    // 点击头像触发file的点击事件
    userimg.addEventListener('click', function () {
        weui.actionSheet([{
            label: '拍照',
            onClick: function () {
                weui.alert('您的设备好像出现了问题')
            }
        }, {
            label: '从相册选择',
            onClick: function () {
                file.click()
            }
        }, {
            label: '其他',
            onClick: function () {
                file.click()
            }
        }], [{
            label: '取消',
            // onClick: function () {
            //     console.log('取消')
            // }
        }], {
            className: 'custom-classname',
            // onClose: function () {
            //     console.log('关闭')
            // }
        });
    })

    let imgSrc = '';
    // 文件上传原理
    file.addEventListener('change', function () {
        // console.dir(this);
        // 获取上传文件的信息
        const fildinfo = this.files[0];
        // 创建formdata对象
        const fd = new FormData();
        // 以键值对的形式添加内容
        fd.append('imgurl', fildinfo);
        // console.log(fd.get('imgurl'));

        // 创建ajax发送数据
        const ajax = new XMLHttpRequest();

        // 创建请求
        ajax.open('post', 'http://139.9.177.51:8099/users/upload');

        // 监听
        ajax.onreadystatechange = function () {
            if (ajax.readyState == 4 && ajax.status == 200) {
                console.log(ajax.responseText);
                userimg.src = 'http://139.9.177.51:8099' + JSON.parse(ajax.responseText).data;
                imgSrc = JSON.parse(ajax.responseText).data;
            }

        }
        ajax.send(fd);

    });

    // // 性别选择
    showgenderPicker.addEventListener('click', function () {
        weui.picker([{
            label: '男',
            value: 1,
        }, {
            label: '女',
            value: 0
        }, {
            label: '其他',
            value: 3
        }], {
            onConfirm: function (result) {
                gender.textContent = result[0].label;
            },
            title: '性别'
        });
    });

    // 生日选择
    showbirthdayPicker.addEventListener('click', function () {
        weui.datePicker({
            start: 1990,
            end: new Date().getFullYear(),
            onConfirm: function (result) {
                const str = result.map((e) => utils.fillZero(e.value)).join('-');
                birthday.textContent = str
            },
            title: '生日选择'
        });
    });

    //省份选择
    address.addEventListener('click', function () {
        
        if(JSON.parse(localStorage.getItem('city'))){
            const city=JSON.parse(localStorage.getItem('city'))
            cityBlock(city)
            return
        }

        // 城市显示函数
        function cityBlock(city) {
            weui.picker(city, {
                onConfirm: function (result) {
                    address.textContent = result[0].label + "-" + result[1].label;
                    console.log(result);
                },
            })
        }


        async function getProvince() {
            const { data } = await axios.get('http://139.9.177.51:8099/address/province')
            const arr = data.data.map((i) => {
                return {
                    label: i.name,
                    value: i.addressId,
                }
            })
            //拼接城市信息
            const city=[]
            arr.forEach(async item => {
                const { data } = await axios.get(`http://139.9.177.51:8099/address/city/${item.value}`)
                // 创建城市数组
                let children = []
                data.data.map( item =>
                    children.push({
                        label: item.name,
                        value: item.addressId
                    })
                )
                city.push({
                    label:item.label,
                    value:item.value,
                    children:children
                })  
            })
            setTimeout(()=>{
                localStorage.setItem('city',JSON.stringify(city))
                cityBlock(city)
            },2000)
        }
        getProvince() 
    })

    // 文本框改变时
    textarea.addEventListener('keyup', function () {
        if (this.value.length > 20) {
            this.value = this.value.substr(0, 20)
        }
        text.textContent = this.value.length;

    })


    // 开始上传信息
    /* imgurl 头像
    nickname 昵称
    gender 性别
    birthday 生日
    address 省市区 城市 数组结构 如[“四川省”, “成都市”]
    sign sign
    userId id */
    // 定义一个对象来存储信息
    save.addEventListener('click', function () {
        // console.log(address.textContent.split('-'));
        const userData = {
            imgurl: imgSrc,
            nickname: nickname.value,
            gender: gender.textContent,
            birthday: birthday.textContent,
            address: address.textContent.split('-'),
            sign: signature.value,
            userId: userId
        }
        axios.post(`${url}/users/userEdit`, userData)
            .then(function (res) {
                console.log(res)
            })
            .catch(function (error) {
                console.log(error)
            })
        const a = JSON.stringify(userData);
        localStorage.setItem('userInfo', a);

        toast.style.display = 'block';
        setTimeout(() => {
            toast.style.display = 'none';
        }, 1000);


        // console.log(userData);
    })














    returnmine.addEventListener('click', function () {
        location.href = './mine.html';
    });

})